<template>
  <div>
    <!-- 搜索 -->
    <!-- 索赔结算单维护--车厂 -->
    <TopFilter
      ref="TopFilterss"
      :list="topFilterInit"
      :cols="3"
      :collapse="collapse"
      labelWidth="110"
      @filterChange="changeHandle"
      @resetChange="resetHandle"
    ></TopFilter>
    <!-- table -->
    <FilterTable
      ref="table"
      :columns="columns"
      :params="fetchParams"
      :fetchapi="fetchapi"
      :datakey="'records'"
      :onColumnsChange="columns => (this.columns = columns)"
      :onRowSelectChange="selectChange"
      :is-select-column="true"
    >
      <template slot="controls" slot-scope="props">
        <!-- <multiuse-button size="small" type="primary" :click="exportFileBtn1.bind()">导出明细</multiuse-button> -->
        <multiuse-button size="small" type="primary" :click="claimExportData">下载</multiuse-button>
        <multiuse-button
          size="small"
          type="primary"
          :click="issusReceipts"
          :disabled="checkSettleType"
        >下发</multiuse-button>
        <multiuse-button size="small" type="primary" :click="closeAccountAll":disabled="disableds">结算</multiuse-button>
      </template>
    </FilterTable>
    <!-- <Drawer :visible.sync="visible" :title="'结算单编辑'" destroyOnClose width="60%" :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <xiangqing @close="close" @save="save" :rowData="rowData"></xiangqing>
    </Drawer>-->
    <BaseDialog :visible.sync="selectDelearFlag" :title="'服务中心选择'" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <DealerList @close="Delearclose" @save="Delearsave" selectionType="multiple"></DealerList>
    </BaseDialog>
    <!-- 结算单详情 -->
    <Drawer
      :visible.sync="claimFlag"
      :title="this.detailTitle"
      destroyOnClose
      width="60%"
      :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }"
    >
      <showDetail @close="close" @save="save" :rowData="rowData"></showDetail>
    </Drawer>
    <!-- <Drawer :visible.sync="claimFlag" :title="'索赔单明细'" destroyOnClose width="60%" :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <ClaimPage @close="claimClose" :rowData="rowData"></ClaimPage>
    </Drawer>-->
    <BaseDialog
      :visible.sync="exportFlag"
      :title="'导出明细'"
      destroyOnClose
      width="80%"
      :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }"
    >
      <ExportSubsidiary @close="exportClose" :rowData="rowData"></ExportSubsidiary>
    </BaseDialog>
  </div>
</template>
<script>
import SearchDealer from '@/pages/omFinance/MoneyManage/ownerSeacher.vue';
import ExportSubsidiary from '@/pages/claimDemage/BasicData/ClaimStatementMaintainFactory/common/ExportSubsidiary.vue';
import DealerList from '@/pages/claimDemage/tools/DealerList.vue';
import ClaimPage from '@/pages/claimDemage/BasicData/ClaimStatementMaintainFactory/common/ClaimPage.vue';
import showDetail from '@/pages/claimDemage/BasicData/ClaimStatementMaintainFactory/common/showDetail.vue';
import { exportExcelFile } from '@/utils/index';
import { getAppId } from '@/assets/js/auth';
import {
  getClaimAccountInfo,
  getPartType,
  quyrPSettle,
  updateSettleStateByNo,
  editSave,
  getListForExport,
  exporturl,
  getClaimListForExport,
  closeAccount
} from '@/api/claim/factory/ClaimStatementQueryFactory';
import { dictionary } from '@/utils/dictMixin';
import moment from 'moment';
export default {
  mixins: [dictionary],
  components: {
    DealerList,
    showDetail,
    ClaimPage,
    ExportSubsidiary,
    SearchDealer
  },
  data() {
    return {
      disableds: false,
      dataList: [],
      checkSettleType: false,
      visible: false,
      visibleDrawer: false,
      collapse: false,
      chakanFlag: false,
      dealerFlag: false,
      isDealer: false,
      dealerData: [],
      selectDelearFlag: false,
      dealerCompanyCode:"",
      detailTitle: '',
      infoId: null,
      editRow: {},
      rowData: {},
      selectDealerData: [],
      topFilterInit: this.topFilterInitFun(),
      flterValue: {}, //参数
      fetchapi: getClaimAccountInfo,
      columns: this.creatHeader(),
      fetchParams: {
        xhrAbort: true,
        status:1
      }, //ipa 接口
      selectedRows: [], //选中服务中心
      visibleAdd: false,
      claimFlag: false,
      exportFlag: false
    };
  },
  created() {
    // if (getAppId() == 'arcfox') {
    //   this.topFilterInit.find(x => x.fieldName == 'carType').itemList =this.createDictList('5543',[55431001])
    // }else{
    //   this.topFilterInit.find(x => x.fieldName == 'carType').itemList =this.createDictList('5543')
    // }
    // this.fetchParams.beginSubmitDate = moment()
    //   .startOf('week')
    //   .format('YYYY-MM-DD HH:mm:ss');
    // this.fetchParams.endSubmitDate = moment()
    //   .endOf('week')
    //   .format('YYYY-MM-DD HH:mm:ss');
    //this.chuqi();
  },
  methods: {
    claimClose() {
      this.claimFlag = false;
    },
    exportClose() {
      this.exportFlag = false;
    },
    seacherFun() {
      this.isDealer = true;
    },
    SelectDelear() {
      this.selectDelearFlag = true;
    },
    //关闭
    Delearclose() {
      this.selectDelearFlag = false;
    },
    resetHandle(val) {
      this.dealerData = [];
      this.selectDealerData = [];
      this.fetchParams = Object.assign({}, this.fetchParams, val, { dealerCompanyCode: null }, { xhrAbort: false });
    },
    //保存
    Delearsave(obj) {
      console.log('选择数据传递', obj);
      this.dealerData = obj;
      this.selectDealerData = [];
      obj.forEach(item => {
        this.selectDealerData.push(item.dealerCompanyCode);
      });
      this.selectDelearFlag = false;
    },
    editClaim(val, type) {
      if (type == 'edit') {
        this.detailTitle = '结算单编辑';
        val = Object.assign({}, val, { detailType: 'edit' });
      } else if (type == 'chakan') {
        this.detailTitle = '结算单明细';
        val = Object.assign({}, val, { detailType: 'chakan' });
      }
      this.rowData = val;
      this.claimFlag = true;
    },
    closeDealer() {
      this.dealerFlag = false;
    },
    saveDealer(obj) {
      this.topFilterInit.map(x => {
        if ('dealerCode' == x.fieldName) {
          x.initialValue = obj[0].dealerCode;
        }
      });
      this.dealerFlag = false;
    },
    chooseDealerNo() {
      this.dealerFlag = true;
    },
    closeAccountAll() {

      this.$confirm('是否确认结算?', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          this.disableds = true;
          closeAccount()
            .then(res => {
              this.$notify.success('结算成功');
              this.fetchParams = { ...this.fetchParams };
            })
            .catch(err => {
              this.$notify.error('结算失败');
            });
        })
        .catch(() => {});
    },
    //对选择的结算单下发
    issusReceipts() {
      if (this.selectedRows.length == 0) {
        this.$message({
          type: 'info',
          message: '请选择对应数据!'
        });
      } else {
        let noList = []; //传入后端的结算单号
        var isTrue = false;

        this.selectedRows.forEach(item => {
          if (item.settleStatus == 50011001) {
            this.$notify.error('已下发的结算单不可再次下发！');
            isTrue = true;
            return;
          }
          noList.push(item.settleNo);
        });
        if (isTrue == true) {
          return;
        }
        let params = { nos: noList };
        updateSettleStateByNo(params)
          .then(res => {
            this.$notify.success('下发成功');
            this.fetchParams = { ...this.fetchParams };
          })
          .catch(err => {
            this.$notify.error('下发失败');
          });
      }
    },
    // 索赔结算单导出
    async claimExportData() {
      await getClaimListForExport(this.fetchParams).then(res => {
        console.log(res);
        exportExcelFile(res.data, '索赔结算单导出');
      });
    },
    emitCloseHandler1(val, data) {
      this.isDealer = val;
      if (data) {
        let dealerCodes = [];
        let dealerNames = [];
        data.map(x => {
          dealerCodes.push(x.dealerCode);
          dealerNames.push(x.dealerName);
        });
        //debugger
        this.topFilterInit.find(x => x.fieldName == 'ownerCode').initialValue = dealerCodes.toString();
      }
    },
    // 导出
    async exportFileBtn() {
      let json = Object.assign({}, { CODE: 'CODE_00000145' }, this.fetchParams);
      let res = await exporturl(json);
      if (res.resultCode == 200) {
        this.$router.push('/admin/auth/oem/downloadCenter');
      }
      // let beginSubmitDate = this.topFilterInit.find(x => x.fieldName == "beginSubmitDate|endSubmitDate").initialValue[0];
      // let endSubmitDate = this.topFilterInit.find(x => x.fieldName == "beginSubmitDate|endSubmitDate").initialValue[1];
      // if(!beginSubmitDate) {
      //   this.$notify.warning({ title: '提示信息', message: '开票开始日期不可为空！' });
      //   return
      // }
      // if(!endSubmitDate) {
      //   this.$notify.warning({ title: '提示信息', message: '开票结束日期不可为空！' });
      //   return
      // }
      // if(getAppId() == 'arcfox') {
      //   if (moment(moment(endSubmitDate).format('YYYY-MM-DD')).diff(moment(beginSubmitDate), 'months', true) > 12) {
      //     this.$notify.warning({ title: '提示信息', message: '开票日期跨度不可超过十二个月！' });
      //     return
      //   }
      // } else {
      //   if (moment(moment(endSubmitDate).format('YYYY-MM-DD')).diff(moment(beginSubmitDate), 'months', true) > 12) {
      //     this.$notify.warning({ title: '提示信息', message: '开票日期跨度不可超过十二个月！' });
      //     return
      //   }
      // }
      // let obj = Object.assign({}, this.fetchParams,{xhrAbort: false, status:1});
      // obj.beginSubmitDate = this.topFilterInit.find(x => x.fieldName == "beginSubmitDate|endSubmitDate").initialValue[0];
      // obj.endSubmitDate = this.topFilterInit.find(x => x.fieldName == "beginSubmitDate|endSubmitDate").initialValue[1];
      // getListForExport(obj).then((res) => {
      //   exportExcelFile(res.data, '索赔结算单信息');
      // });
    },
    // exportFileBtn1() {
    //   this.exportFlag = true;
    // },
    // 删除
    async delFun(val) {
      this.$confirm('确定删除吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        this.res = await deleteOne(val.settleId);
        if (this.res.resultCode != 200) {
          this.$notify.error({ title: '提示信息', message: res.errMsg || '删除失败!' });
        } else {
          this.$notify.success({ title: '提示信息', message: '删除成功!' });
          this.fetchParams = { ...this.fetchParams };
        }
      });
    },
    //翻译
    async chuqi() {
      // const res = await getPartType({ type: 5548 });
      // delete res.data[0];
      // delete res.data[2];
      // delete res.data[4];
      // // delete res.data[5];
      // if (res.resultCode == 200) {
      //   this.topFilterInit.find((x) => x.fieldName == 'batchStatus').initialValue = '';
      //   this.topFilterInit.find((x) => x.fieldName == 'batchStatus').itemList = res.data.map((y) => ({ text: y.codeCnDesc, value: y.codeId }));
      // }
      // const res4 = await getPartType( {type:5543});
      // if (res4.resultCode == 200) {
      //
      //   if (getAppId() == 'arcfox') {
      //     delete res4.data[0];
      //   }
      //
      //   this.topFilterInit.find(x => x.fieldName == 'carType').initialValue = '';
      //   this.topFilterInit.find(x => x.fieldName == 'carType').itemList = res4.data.map(y =>({ text: y.codeCnDesc, value: y.codeId }));
      // }
    }, // 提交
    async submitFun(val) {
      this.$confirm('确定提交吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        let res1 = await quyrPSettle(val.settleId);
        this.editRow = res1.data;
        //状态改成提交
        this.editRow.settleStatus = 55461002;
        let res = await editSave(this.editRow);
        if (res.resultCode != 200) {
          this.$notify.error({ title: '提示信息', message: res.errMsg || '提交失败!' });
        } else {
          this.$notify.success({ title: '提示信息', message: '提交成功!' });
          this.fetchParams = { ...this.fetchParams };
        }
      });
    },
    //选中
    selectChange(rows) {
      this.selectedRows = rows;
      this.selectedRows.forEach(v => {
        if (v.settleStatus == 50011001) {
          this.checkSettleType = true;
          return true;
        } else {
          this.checkSettleType = false;
        }
      });
    },
    close() {
      this.claimFlag = false;
      this.fetchParams = { ...this.fetchParams };
    },
    chakan(val) {
      this.rowData = val;
      this.chakanFlag = true;
    },
    save(obj) {
      this.visible = false;
      this.fetchParams = { ...this.fetchParams };
    },
    //搜索获取数据
    changeHandle(val) {
      // 以下注释为了跳过校验查数据，记得放开
      // if(!val.beginSubmitDate) {
      //   this.$notify.warning({ title: '提示信息', message: '开票开始日期不可为空！' });
      //   return
      // }
      // if(!val.endSubmitDate) {
      //   this.$notify.warning({ title: '提示信息', message: '开票结束日期不可为空！' });
      //   return
      // }
      // if(getAppId() == 'arcfox') {
      //   if (moment(moment(val.endSubmitDate).format('YYYY-MM-DD')).diff(moment(val.beginSubmitDate), 'months', true) > 12) {
      //     this.$notify.warning({ title: '提示信息', message: '开票日期跨度不可超过十二个月！' });
      //     return
      //   }
      // } else {
      //   if (moment(moment(val.endSubmitDate).format('YYYY-MM-DD')).diff(moment(val.beginSubmitDate), 'months', true) > 12) {
      //     this.$notify.warning({ title: '提示信息', message: '开票日期跨度不可超过十二个月！' });
      //     return
      //   }
      // }
      this.fetchParams = Object.assign({}, this.fetchParams, val, { dealerCode: this.searchDealerCode, dealerCompanyCode: this.selectDealerData.length ?  this.selectDealerData : null}, { xhrAbort: false });
      console.log(val);
    },
    //搜索数据
    topFilterInitFun() {
      return [
        {
          type: 'INPUT',
          label: '服务中心',
          render: (p) => {
            return (
              <div>
                <el-select v-model={this.selectDealerData} disabled={true} multiple placeholder="请选择">
                  {this.dealerData.map((item) => (
                    <el-option key={item.dealerCode} label={item.dealerShortname} value={item.dealerCompanyCode} />
                  ))}
                </el-select>
                <multiuse-button style="position: absolute;right: 0;height:100%" icon="el-icon-search" onClick={() => this.selectDelearFlag = true} />
              </div>
            );
          },
        },
        { type: 'INPUT', label: '结算单号', fieldName: 'settleNo', placeholder: '请输入结算单号...', initialValue: '' },
        { type: 'SELECT', label: '结算状态', fieldName: 'settleStatus', placeholder: '请选择结算状态...', initialValue: '', itemList: this.createDictList('5001') },
        { type: 'INPUT', label: '结算月份', fieldName: 'settleDate', placeholder: '请输入结算月份...', initialValue: '' },
        {
          type: 'RANGE_DATE',
          label: '下发时间',
          fieldName: 'beginIssueDate|endIssueDate',
          placeholder: '请输入',
          dateType: 'datetimerange',
          // initialValue: [
          //   moment(new Date())
          //     .subtract(6, 'month')
          //     .format('YYYY-MM-DD 00:00:00'),
          //   moment(new Date()).format('YYYY-MM-DD 23:59:59')
          // ],
         // rules: [{ required: false, message: '请选择日期', trigger: 'change' }] //方便搜索查数据，记得放开
        },
        // { type: 'SELECT', label: '索赔车辆属性', fieldName: 'carType', placeholder: '请选择索赔车辆属性...', initialValue: '', itemList: this.createDictList('5543') }
      ];
    },
    //table表头和数据源
    creatHeader() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          fixed: 'left',
          width: 80,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 120,
          render: (props, h) => {
            return (
              <div>
                <multiuse-button size="mini" type="text" onClick={() => this.editClaim(props.row, 'chakan')}>
                  明细
                </multiuse-button>
                <multiuse-button size="mini" type="text" onClick={() => this.editClaim(props.row, 'edit')}
                disabled={props.row.settleStatus == '50011001' ? true : false}>
                  编辑
                </multiuse-button>
              </div>
            );
          }
        },
        { title: '结算单状态', dataIndex: 'settleStatus', sorter: true, showOverflowTooltip: true, dictItems: this.createDictList('5001') },
        { title: '结算单号', dataIndex: 'settleNo', sorter: true },
        { title: '结算月份', dataIndex: 'settleDate', sorter: true },
        { title: '结算单类型', dataIndex: 'finalStatementType', dictItems: this.createDictList('5002') },
        { title: '服务中心代码', dataIndex: 'dealerCode', sorter: true },
        { title: '服务中心简称', dataIndex: 'dealerName', sorter: true },
        { title: '索赔单数', dataIndex: 'claimSum', sorter: true },
        { title: '结算金额', dataIndex: 'settleAmount', sorter: true }

        // {title: '结算批次号', dataIndex: 'batchNo', sorter: true},

        // { title: '索赔车辆属性', dataIndex: 'carTypeStr', sorter: true },
        // { title: '索赔单数', dataIndex: 'claimNum', sorter: true },
        // { title: '考核金额', dataIndex: 'assessSum', sorter: true },
        // {title: '索赔金额', dataIndex: 'claimSum', sorter: true},

        // { title: '开票时间', dataIndex: 'submitDate', sorter: true },
        // { title: '邮寄时间', dataIndex: 'sendDate', sorter: true },
        // { title: '审核时间', dataIndex: 'approveDate', sorter: true },
        // { title: '结算时间', dataIndex: 'settleDate', sorter: true },
        // { title: '主键', dataIndex: 'batchId', hidden: true },
      ];
    }
  }
};
</script>

<style lang="less" scoped></style>
